import { useMemo, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { changeWidgets } from '@/store/modules/core'
import useWidget from '@/hooks/useWidget'
import Chart from '../../Chart'
import styleBaseConfig from '../Style/baseInfo'
import { configsTodefaultValue } from '@/utils/core'

function getDefaultValueForGlobalChart(type, chartValues = {}) {
  if (!Chart.has(type)) return

  const keys = [
    'backgroundColor',
    'titleEnabled',
    'title',
    'iconEnabled',
    'icon',
    'splitLineEnabled',
    'splitLine'
  ]
  const obj = {}
  keys.forEach((key) => {
    if (key in chartValues) {
      obj[key] = chartValues[key]
    }
  })
  return obj
}

function useStyle() {
  const dispatch = useDispatch()
  const { widgets, selectedWidgetIds, selectedWidget } = useWidget()
  const globalValue = useSelector((state) => state.core.globalValue)
  const commonValue = useMemo(
    () => getDefaultValueForGlobalChart(selectedWidget?.type, globalValue?.chart),
    [selectedWidget, globalValue]
  )

  const styleConfigs = useMemo(() => {
    if (!selectedWidgetIds || selectedWidgetIds.length === 0) return
    const chartConfig = Chart.getConfigs(selectedWidget.type)
    return {
      base: {
        label: '基础信息',
        options: styleBaseConfig
      },
      ...chartConfig
    }
  }, [selectedWidgetIds])

  const styleData = useMemo(() => {
    if (!styleConfigs) return
    const { styleValue } = selectedWidget
    if (styleValue === undefined) {
      const defaultValue = configsTodefaultValue(styleConfigs)
      const { backgroundColor, ...common } = commonValue
      const background = {
        ...defaultValue.base.background,
        color: backgroundColor
      }
      return {
        ...defaultValue,
        base: {
          ...defaultValue.base,
          ...common,
          background
        }
      }
    }
    return styleValue
  }, [styleConfigs, selectedWidget])

  useEffect(() => {
    if (styleData) {
      onStyleChange(styleData)
    }
  }, [styleData])

  const onStyleChange = (value) => {
    const newWidgets = {
      ...widgets,
      [selectedWidgetIds[0]]: {
        ...selectedWidget,
        styleValue: value
      }
    }
    dispatch(changeWidgets(newWidgets))
  }

  return [styleConfigs, styleData, onStyleChange]
}

export default useStyle
